package cn.sytton.taffe.excel.util;

import cn.hutool.core.bean.BeanUtil;
import cn.sytton.taffe.excel.model.ExcelField;
import cn.sytton.taffe.excel.model.ExcelFormat;
import cn.sytton.taffe.excel.model.ExcelParam;
import com.github.pagehelper.PageInfo;
import cn.sytton.taffe.excel.ExcelExport;
import cn.sytton.taffe.framework.util.JsonUtil;

import java.util.*;

/**
 * 导出Excel工具类, 使用于PageInfo对象
 *
 * @author skyrock
 */
public class PageToExcel {
    public static void export(Map<String, Object> exportParams, PageInfo<?> pageInfo) {
        ExcelParam ep = transParams(exportParams);
        ExcelExport excelUtil = new ExcelExport();
        excelUtil.exportExcel(ep.getName(), ep.getFields(), pageInfo.getList(), ep.getFormat());
    }

    @SuppressWarnings("unchecked")
    private static ExcelParam transParams(Map<String, Object> export) {
        ExcelParam param = BeanUtil.fillBeanWithMap(export, new ExcelParam(), true);
        if (param.getFormat() == null) {
            param.setFormat(new HashMap<>());
        }
        Map<String, Object> formatMap = JsonUtil.getEntity(export.get("format").toString());
        formatMap.forEach((k,v)->{
            Map<String, ExcelFormat> paramMap = new HashMap<>();
            ((List<Object>)v).forEach(o -> {
                ExcelFormat ef = BeanUtil.fillBeanWithMap((Map<?, ?>) o,
                        new ExcelFormat(),
                        true);
                paramMap.put(ef.getValue(), ef);
            });
            param.getFormat().put(k, paramMap);
        });
        param.setFields(Arrays.asList(Objects.requireNonNull(JsonUtil.getEntity(export.get("fields").toString(), ExcelField[].class))));
        return param;
    }
}
